package com.example.tools;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用于实现两个人之间的数据交换，每个人在完成一定的事务后想与对方交换数据，
 * 第一个先拿出数据的人将一直等待第二个人拿着数据到来时，才能彼此交换数据。
 */
public class ExchangerTest {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Exchanger exchanger = new Exchanger();

        executorService.execute(new Runnable() {

            public void run() {

                try {
                    String data1 = "毒品";
                    System.out.println("线程" + Thread.currentThread().getName() + "正在把" + data1 + "换出去");
                    Thread.sleep((long) (Math.random() * 10000));
                    String data2 = (String) exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() + "换回" + data2);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(new Runnable() {

            public void run() {

                try {
                    String data1 = "美金";
                    System.out.println("线程" + Thread.currentThread().getName() + "正在把" + data1 + "换出去");
                    Thread.sleep((long) (Math.random() * 10000));
                    String data2 = (String) exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() + "换回" + data2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        });
    }
}
